<template>
  <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="true" :show-close="false" :modal="true"
    :modal-append-to-body="true" width="420px" custom-class="login-dialog" center>
    <div class="login-dialog-content">
      <h3>{{ isRegister ? '用户注册' : '管理员登录' }}</h3>

      <!-- 登录表单 -->
      <el-form v-if="!isRegister" :model="loginForm" label-width="0" ref="loginForm">
        <el-form-item>
          <el-input v-model="loginForm.account" placeholder="请输入账号" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" prefix-icon="el-icon-lock"
            @keyup.enter.native="handleLogin"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="form-footer-row">
            <el-checkbox v-model="loginForm.checked">记住密码</el-checkbox>
            <span class="switch-text" @click="switchToRegister">还没有账号？点击注册</span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form v-else :model="registerForm" label-width="0" ref="registerForm">
        <el-form-item>
          <el-input v-model="registerForm.account" placeholder="请输入账号" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user-solid"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"
            prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input type="password" v-model="registerForm.password2" placeholder="请再次输入密码" prefix-icon="el-icon-lock"
            @keyup.enter.native="handleRegister"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="form-footer-row">
            <span></span>
            <span class="switch-text" @click="switchToLogin">已有账号？前往登录</span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" style="width: 100%">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { adminLogin, userRegister, userLogin } from "../api/index"

const hide = (value) => {
  return value
}

const show = (txt) => {
  return txt
}

export default {
  name: 'LoginDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      isRegister: false,
      loginForm: {
        account: "",
        password: "",
        checked: false
      },
      registerForm: {
        account: "",
        username: "",
        password: "",
        password2: ""
      }
    }
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal
      if (newVal) {
        this.loadRememberedPassword()
      }
    },
    dialogVisible(newVal) {
      if (!newVal) {
        this.$emit('update:visible', false)
        this.$emit('close')
      }
    }
  },
  methods: {
    switchToRegister() {
      this.isRegister = true
      this.$nextTick(() => {
        if (this.$refs.registerForm) {
          this.$refs.registerForm.clearValidate()
        }
      })
    },
    switchToLogin() {
      this.isRegister = false
      this.$nextTick(() => {
        if (this.$refs.loginForm) {
          this.$refs.loginForm.clearValidate()
        }
      })
    },
    loadRememberedPassword() {
      let acc = localStorage.getItem("XXXXA")
      let pwd = localStorage.getItem("XXXXP")
      if (acc != null && pwd != null) {
        this.loginForm.account = show(acc)
        this.loginForm.password = show(pwd)
        this.loginForm.checked = true
      } else {
        this.loginForm.account = ""
        this.loginForm.password = ""
        this.loginForm.checked = false
      }
    },
    async handleLogin() {
      let account = this.loginForm.account
      let password = this.loginForm.password
      let checked = this.loginForm.checked

      if (account == "" || password == "") {
        this.$message({
          message: "输入框不能为空",
          type: "error"
        })
        return false
      }

      try {
        const resData = await adminLogin({ account, password })
        if (resData.code == 200) {
          let account = resData.account
          let username = resData.username
          let token = resData.token
          let role = resData.role || '1'

          localStorage.setItem("AUTO_TOKEN", token)
          localStorage.setItem("USERNAME", username)
          localStorage.setItem("ACCOUNT", account)
          localStorage.setItem("USER_ROLE", role)

          if (checked) {
            localStorage.setItem("XXXXA", hide(account))
            localStorage.setItem("XXXXP", hide(password))
          } else {
            localStorage.removeItem("XXXXA")
            localStorage.removeItem("XXXXP")
          }

          this.$message({
            type: "success",
            message: "登录成功"
          })

          this.dialogVisible = false
          this.$emit('login-success')
        } else {
          this.$message({
            type: "error",
            message: resData.msg || "登录失败"
          })
        }
      } catch (error) {
        this.$message({
          type: "error",
          message: "登录失败，请稍后重试"
        })
      }
    },
    async handleRegister() {
      let { account, username, password, password2 } = this.registerForm

      if (!account || !username || !password || !password2) {
        this.$message({
          message: "请填写完整信息",
          type: "error"
        })
        return false
      }

      if (password !== password2) {
        this.$message({
          message: "两次输入的密码不一致",
          type: "error"
        })
        return false
      }

      if (password.length < 6) {
        this.$message({
          message: "密码长度至少为6位",
          type: "error"
        })
        return false
      }

      try {
        const resData = await userRegister({
          account,
          username,
          password,
          gender: "",
          imgUrl: ""
        })

        if (resData.code == 200) {
          this.$message({
            type: "success",
            message: resData.msg || "注册成功"
          })

          try {
            const loginResData = await userLogin({ account, password })
            if (loginResData.code == 200) {
              let account = loginResData.account
              let username = loginResData.username
              let token = loginResData.token
              let role = loginResData.role || '0'

              localStorage.setItem("AUTO_TOKEN", token)
              localStorage.setItem("USERNAME", username)
              localStorage.setItem("ACCOUNT", account)
              localStorage.setItem("USER_ROLE", role)

              this.$message({
                type: "success",
                message: "注册成功，已自动登录"
              })

              this.dialogVisible = false
              this.$emit('login-success')
            } else {
              this.$message({
                type: "warning",
                message: "注册成功，但自动登录失败，请手动登录"
              })
              this.switchToLogin()
              this.loginForm.account = account
            }
          } catch (loginError) {
            this.$message({
              type: "warning",
              message: "注册成功，但自动登录失败，请手动登录"
            })
            this.switchToLogin()
            this.loginForm.account = account
          }
        } else {
          this.$message({
            type: "error",
            message: resData.msg || "注册失败"
          })
        }
      } catch (error) {
        this.$message({
          type: "error",
          message: "注册失败，请稍后重试"
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-dialog-content {
  padding: 20px;

  h3 {
    text-align: center;
    margin-bottom: 30px;
    color: #303133;
    font-size: 24px;
    font-weight: 500;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .form-footer-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .switch-text {
      color: #409eff;
      cursor: pointer;
      font-size: 14px;
      user-select: none;

      &:hover {
        color: #66b1ff;
        text-decoration: underline;
      }
    }
  }
}
</style>

<style lang="less">
.login-dialog {
  .el-dialog {
    border-radius: 8px;
    margin-top: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: 0 !important;
  }

  .el-dialog__header {
    display: none;
  }

  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__wrapper {
    background-color: rgba(0, 0, 0, 0.5) !important;
  }
}

.el-dialog__wrapper.login-dialog {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
}
</style>
